﻿using Demo.Net.EFCoreEnv.Dbcontexts;
using IRepository;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Repository
{
    public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class, new()
    {
        protected Parking context;
        //数据添加
        public async Task<bool> Add(TEntity entity)
        {
            await context.Set<TEntity>().AddAsync(entity);
            return await context.SaveChangesAsync() > 0;
        }
        //数据删除
        // public async Task<bool> Delete(TEntity entity)
        // {
        //     context.Set<TEntity>().Update(entity);
        //     return await context.SaveChangesAsync() > 0;
        // }
        //条件查询
        public async Task<List<TEntity>> Find(Expression<Func<TEntity, bool>> exp)
        {
            return await context.Set<TEntity>().Where(exp).ToListAsync();
        }
        //查询全部
        public async Task<List<TEntity>> FindAll()
        {
            return await context.Set<TEntity>().ToListAsync();
        }
        
        //模糊查询
         public async Task<List<TEntity>> FindAllByCondition(Expression<Func<TEntity, bool>> searchTerm)
        {
            return await context.Set<TEntity>().Where(searchTerm).ToListAsync();
        }

        //数据编辑
        public async Task<bool> UpdateAsync(TEntity entity)
        {
            context.Set<TEntity>().Update(entity);
            return await context.SaveChangesAsync() > 0;
        }

       //删除
        public async Task<bool> Delete(int id)
        {
            var entity = await context.Set<TEntity>().FindAsync(id);
            if (entity == null)
            {
                return false;
            }
            context.Set<TEntity>().Remove(entity);
            return await context.SaveChangesAsync() > 0;
        }

    }
}
